<template>
  <div>
    <!-- 插槽 -->
    <slot />
    <!-- tabbar -->
    <ClientOnly>
      <van-tabbar
        class="tabbar"
        :class="{ 'tabbar-iOS': globalStore.$state.IsIphoneX }"
        ref="tabbarRef"
        fixed
        :border="false"
        safe-area-inset-bottom
        v-model="active"
        z-index="999998"
        @change="onChange"
      >
        <van-tabbar-item>
          <span>{{ icons[0].title }}</span>
          <template #icon="props">
            <img
              class="tabbar-item-icon"
              :src="props.active ? icons[0].active : icons[0].inactive"
            />
          </template>
        </van-tabbar-item>
        <van-tabbar-item :dot="globalStore.$state.isTabBarRewardsDot">
          <span>{{ icons[1].title }}</span>
          <template #icon="props">
            <img
              class="tabbar-item-icon"
              :src="props.active ? icons[1].active : icons[1].inactive"
            />
          </template>
        </van-tabbar-item>
        <van-tabbar-item :badge="boxs">
          <span style="position: relative; top: -8.5px">{{
            icons[2].title
          }}</span>
          <template #icon="props">
            <div
              class="tabbar-item-center items-center"
              :class="{
                'tabbar-item-center-activity': props.active,
              }"
            >
              <img
                class="tabbar-item-icon"
                :src="props.active ? icons[2].active : icons[2].inactive"
              />
            </div>
          </template>
        </van-tabbar-item>
        <van-tabbar-item
          icon="setting-o"
          :dot="globalStore.$state.isTabBarPledgeDot"
        >
          <span>{{ icons[3].title }}</span>
          <template #icon="props">
            <img
              class="tabbar-item-icon"
              :src="props.active ? icons[3].active : icons[3].inactive"
            />
          </template>
        </van-tabbar-item>
        <van-tabbar-item icon="setting-o">
          <span>{{ icons[4].title }}</span>
          <template #icon="props">
            <img
              class="tabbar-item-icon"
              :src="props.active ? icons[4].active : icons[4].inactive"
            />
          </template>
        </van-tabbar-item>
      </van-tabbar>
    </ClientOnly>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { useEventBus } from "@vueuse/core";
import { useGlobalStore } from "~~/store/global";
import { getBoxList, getRewardInfo } from "@/api/bdc";
import { getOssFileUrl, isiOS } from "@/utils";

const globalStore = useGlobalStore();
const route = useRoute();
console.log("布局 tabbar 参数:", route.query);
const { t } = useI18n();
const imgUrl = getOssFileUrl({
  coin: "/image/tabbar/coin.png",
  coin_jh: "/image/tabbar/coin-jh.png",
  rewards: "/image/tabbar/rewards.png",
  rewards_jh: "/image/tabbar/rewards-jh.png",
  mining: "/image/tabbar/mining.png",
  mining_jh: "/image/tabbar/mining-jh.png",
  pledge: "/image/tabbar/pledge.png",
  pledge_jh: "/image/tabbar/pledge-jh.png",
  asset: "/image/tabbar/asset.png",
  asset_jh: "/image/tabbar/asset-jh.png",
});

const icons = ref([
  {
    title: "Coin",
    inactive: imgUrl.coin,
    active: imgUrl.coin_jh,
  },
  {
    title: t("activity.title.rewards"),
    inactive: imgUrl.rewards,
    active: imgUrl.rewards_jh,
  },
  {
    title: "Mining",
    inactive: imgUrl.mining,
    active: imgUrl.mining_jh,
  },
  {
    title: t("activity.title.pledge"),
    inactive: imgUrl.pledge,
    active: imgUrl.pledge_jh,
  },
  {
    title: t("activity.title.assets"),
    inactive: imgUrl.asset,
    active: imgUrl.asset_jh,
  },
]);

// iOS 除去底部安全区域,页面高度
const innerWidth = ref(0);
const heightiOS = computed(() => {
  if (process.client) {
    let h = 50;
    if (innerWidth.value) {
      h = (50 / 393) * innerWidth.value;
    }
    if (isiOS.value) {
      if (globalStore.$state.IsIphoneX) {
        return `calc(100vh - ${h + 34}px)`;
      } else {
        return `calc(100vh - ${h}px)`;
      }
    } else {
      return `calc(100vh - ${h}px)`;
    }
  }
  return `calc(100vh - ${h}px)`;
});

const tabbarRef = ref();
const tabBarEmit = useEventBus("tab-bar-jump-emit");
const switchTabBarEmit = useEventBus("tab-bar-jump-on");

const active = ref(0);
// 根据页面传参确定激活的 tab 的索引
if (route.query.idx) {
  active.value = Number(route.query.idx);
  globalStore.$patch((state) => {
    state.tabBarIdx = Number(route.query.idx);
  });
} else if (globalStore.$state.tabBarIdx >= 0) {
  active.value = globalStore.$state.tabBarIdx;
} else {
  active.value = 0;
}

const onChange = (val: string | number) => {
  // 1. 赋值.保存
  active.value = Number(val);
  globalStore.$patch((state) => {
    state.tabBarIdx = Number(val);
  });
  // 2. 通知:同步切换页面
  tabBarEmit.emit(val);
  // 3. 🔴消失逻辑,要保存到 stroe 中去(避免重新加载页面的时候再出现)
  if (val == 1 && globalStore.$state.isTabBarRewardsDot) {
    globalStore.$patch((state) => {
      state.isTabBarRewardsDot = false;
    });
  }
  if (val == 3 && globalStore.$state.isTabBarPledgeDot) {
    globalStore.$patch((state) => {
      state.isTabBarPledgeDot = false;
    });
  }
};
// 如果 使用tabBar 跳转方式
switchTabBarEmit.on((idx: any) => {
  console.log("--layouts-tabBar--", idx);
  onChange(idx);
});

// 未开箱数量
const boxs = ref(null);

const getBoxListRequest = async () => {
  getBoxList({
    pageNum: 1,
    pageSize: 1,
  }).then((res: any) => {
    if (res && Number(res.total) > 0) boxs.value = res.total;
  });
};

const tabBarBadgeEmit = useEventBus("tab-bar-badge-on");
onMounted(() => {
  // 0. 获取页面宽度
  innerWidth.value = window.innerWidth;
  // 1. 获取宝箱列表,有的话就显示红点: route.fullPath != "/tabbar?idx=2" 避免进入挖矿页面连续请求两次,后端同一个账户会加锁,两次连续请求可能会出错
  if (route.fullPath != "/tabbar?idx=2" || active.value != 2) {
    getBoxListRequest();
  }
  // 1.1 获取🔴信息;
  getRewardInfo().then((res) => {
    // console.log("-🔴信息", res);
    if (res) {
      if (
        res.profitAmount &&
        globalStore.$state.isTabBarPledgeDot === undefined
      ) {
        // 如果进入的当前页面有红点,则无需再展示了
        globalStore.$patch((state) => {
          state.isTabBarPledgeDot =
            active.value != 3 ? Number(res.profitAmount) >= 1 : false;
        });
      }
      if (globalStore.$state.isTabBarRewardsDot === undefined) {
        globalStore.$patch((state) => {
          state.isTabBarRewardsDot =
            active.value != 1 ? !!res.airdropActivityPendingClaim : false;
        });
      }
    }
  });

  // 2. 动态更新 badge
  tabBarBadgeEmit.on((val: any) => {
    if (val < 1) {
      boxs.value = null;
    } else boxs.value = val;
  });
});
</script>

<style lang="scss" scoped>
.tabbar {
  box-shadow: 0px -15px 20px 5px rgba(0, 62, 128, 0.04);
  &-iOS {
    bottom: 34 * 2px; // iOS safe-area-inset-bottom变量失效, 使用默认间距34px
  }
  &-item {
    &-center {
      position: relative;
      top: -15px;
      justify-content: center;
      background-color: #f3f3f5;
      width: 44 * 2px;
      height: 44 * 2px;
      border-radius: 44 * 2px;
      &-activity {
        background-color: #dfeeff;
      }
    }

    &-icon {
      width: 24 * 2px;
      height: 24 * 2px;
    }
  }
}
.footer {
}
</style>
<style lang="scss">
.tabbar {
  &-iOS {
    &-height {
      height: v-bind("heightiOS") !important;
    }
  }
  .van-badge--top-right {
    top: -7.5px !important;
  }
}
</style>
